--#include "data\config\Fuben\SpaceTrialConfig.lua" once   --血域试炼

SPACETRIAL_MY_DONE_TIMES		= 1     --进入副本次数

SPACETRIAL_BOSS_IDX_PLAYING		= 1		--正在打第N个BOSS
SPACETRIAL_BOSS_BEGINPLAYTIME	= 2		--打当前BOSS的开始时间
SPACETRIAL_BOSS_ALLPLAYTIME		= 3		--打当前BOSS的总时间
SPACETRIAL_BOSS_KILLSCORE		= 4		--当前BOSS击杀积分

SpaceTrialWeekRankColumn = 
{	
	{"name"},				--0，玩家Name
	{"serverId"},			--1，玩家ServerId(留空)
	{"job"},				--2，玩家职业
}

SpaceTrialWeekRank 		= Lang.Rank.SpaceTrialWeekRank			--血域试炼周榜
SpaceTrialWeekLastRank 	= Lang.Rank.SpaceTrialWeekLastRank		--血域试炼上周榜


function GmDoSpaceTrial( sysarg, flag, param )
	print("GmDoSpaceTrial, flag="..flag..", param="..param)
	if flag == 1 then
		local sVar = Actor.getStaticVar(sysarg)
		sVar.spaceTrialFirstKillBoss = nil
		sVar.spaceTrialData = nil
	elseif flag == 2 then					--跨天处理
		SpaceTrialActorDailyProc( sysarg )
	elseif flag == 3 then
		SpaceTrialMondayProc() 				--每周一0点处理
	end
end

--[[
注册一些事件
]]
function ResisterSpaceTrialProc()
	--print("ResisterSpaceTrialProc...")
	SceneHandExitDispatcher.register( SpaceTrialCfg.sceneId,  OnHandExitSpaceTrial )			--注册离开场景、副本后触发的事件
	FubenTimeoutDispatcher.register( SpaceTrialCfg.fubenId, OnSpaceTrialTimeout )				--注册场景、副本时间到后触发的事件
	SceneLogoutDispatcher.register( SpaceTrialCfg.sceneId, OnLogoutSpaceTrial )					--注册场景、副本中下线触发的事件
end


--[[
副本时间到
]]
function OnSpaceTrialTimeout( fubenPtr )
	local actorId 	= Fuben.getOwnerId( fubenPtr )
	local actorPtr 	= Actor.getActorById( actorId )
	if actorPtr and IsInSpaceTrial( actorPtr ) then 		--玩家在线并且在副本中
		OnSpaceTrialOver( actorPtr, fubenPtr, 1 )			--副本打完
	end
end

--[[
个人BOSS副本中下线
]]
function OnLogoutSpaceTrial( sysarg )
	local sceneId 	= Actor.getSceneId( sysarg )
	local fubenPtr 	= Actor.getFubenPrt(sysarg)
	local fubenId 	= Fuben.getFuBenId(fubenPtr)

	--print("OnLogoutSpaceTrial, sceneId="..sceneId..", fubenId="..fubenId)
	DroplineSaveFubenHandler( sysarg )

	local actorId 	= Actor.getActorId( sysarg )
	local actorName	= Actor.getName( sysarg )
	local sceneId 	= Actor.getSceneId( sysarg )
	local fubenId 	= Actor.getFubenId( sysarg )
	System.sendCommonLog( GameLog.clFubenDropReset_Logout, actorId, actorName , 0, sceneId, fubenId,'','',"fuben logout")
end

--[[
副本中恢复上线
]]
function ProcLoginSpaceTrial( sysarg, fubenPtr  )
	--print("ProcLoginSpaceTrial...")
	if not fubenPtr then
		return
	end

	if IsInSpaceTrial( sysarg ) then
		return
	end

	local fubenId  = Fuben.getFuBenId( fubenPtr )

	local actorId 	= Actor.getActorId( sysarg )
	local actorName	= Actor.getName( sysarg )
	System.sendCommonLog( GameLog.clFubenDropReset_LoginTry, actorId, actorName , 0, 0, fubenId,'','', "spacetrial login" )

	
	local fubenHandle = Fuben.getFubenHandle( fubenPtr )
	--print("ProcLoginMagicCity, fubenHandle="..fubenHandle)
	if fubenHandle <= 0 then
		return
	end

	if not Fuben.isFubenExist( fubenHandle ) then			--副本已经不存在（被撤销）了
		return
	end

	--这里预防曾经有某玩家保存的副本handle正好与此副本相同的情况
	local actorId = Actor.getActorId( sysarg )
	local ownerId = Fuben.getOwnerId( fubenPtr )			--副本Owner
	--print("ProcLoginMagicCity, actorId="..actorId..", ownerId="..ownerId)
	if actorId ~= ownerId then
		return
	end
	
	local enterPos = SpaceTrialCfg.enterPos
	if Actor.enterFuBen( sysarg, fubenHandle, SpaceTrialCfg.sceneId, enterPos[1], enterPos[2] ) then
		OpenSpaceTrialPanel( sysarg )
		System.sendCommonLog( GameLog.clFubenDropReset_LoginOk, actorId, actorName , 0, SpaceTrialCfg.sceneId, fubenId,
			'', '', "spacetrial login ok" )
	end
end

--[[
手工离开场景
1、手工离开，如果怪物没有击杀完毕，算通关失败
]]
function OnHandExitSpaceTrial( sysarg )
	--print("OnHandExitSpaceTrial")
	if not IsInSpaceTrial( sysarg ) then
		return
	end

	local fubenPtr = Actor.getFubenPrt( sysarg )
	local fubenHandle = Fuben.getFubenHandle( fubenPtr )
	local bossIdx = Fuben.getFbValue( fubenPtr, SPACETRIAL_BOSS_IDX_PLAYING )			--准备开始战斗的BOSS
	if bossIdx <= 1 then
		OnSpaceTrialOver( sysarg, fubenPtr, 0 )		--一个BOSS没击杀，算失败
	elseif bossIdx <= #SpaceTrialCfg.boss then		
		OnSpaceTrialOver( sysarg, fubenPtr, 2 )		--没打完就退出
	else
		OnSpaceTrialOver( sysarg, fubenPtr, 1 )		--全部打完算成功
	end
	Fuben.setFubenTime( fubenHandle, 1 )			--手工离开，关闭副本
end


function InitSpaceTrialWeekRank()
	--print("*****>>InitSpaceTrialWeekRank...")
	Rank.Init(SpaceTrialWeekRank, SpaceTrialWeekRank, SpaceTrialWeekRankColumn, 1500, 0)
end

--[[
每周一零点处理
]]
function SpaceTrialMondayProc()
	--SendCommonRankAwards( enCommonRankType_SpaceTrialWeek, SpaceTrialCfg.weekRank ) 			--周榜发奖
	SendCommonRankAwards( enCommonRankType_SpaceTrialWeek ) 									--周榜发奖
end


--[[
跨天数据重置
]]
function SpaceTrialActorDailyProc( sysarg )
	--print("SpaceTrialActorDailyProc...")
	SetSpaceTrialMyValue( sysarg, SPACETRIAL_MY_DONE_TIMES, 0  )			--进入次数清0
end


--[[
进入血域试炼
]]
function EnterSpaceTrial( sysarg )
	if IsInSpaceTrial( sysarg ) then
		Actor.sendTipmsg( sysarg, Lang.ScriptTips.COM0068, ttFlyTip )
		return
	end

	if CommonEnterScence( sysarg, SpaceTrialCfg, GameLog.clSpaceTrialEnterFee, Lang.ScriptTips.SpaceTrialLog01,
		 CheckEnterSpaceTrial, BeforeEnterSpaceTrial ) then
		--InitSpaceTrialData( sysarg )

		local actorId 	= Actor.getActorId( sysarg )
		local fubenPtr 	= Actor.getFubenPrt( sysarg )
		Fuben.setOwnerId( fubenPtr, actorId )

		Fuben.setFbValue( fubenPtr, SPACETRIAL_BOSS_IDX_PLAYING, 0 )			--准备开始战斗的BOSS
		Fuben.setFbValue( fubenPtr, SPACETRIAL_BOSS_KILLSCORE, 0 )				--BOSS击杀积分清0
		FreshSpaceTrialBoss( fubenPtr, 0 ) 		--刷出下一个BOSS
		OpenSpaceTrialPanel( sysarg )

		Fuben.clearAwardsMerged( fubenPtr )			--清除副本奖励统计
	end
end

--[[
下发血域试炼排行榜数据
]]
function SendSpaceTrialRank( sysarg )
	--SendCommonRankSimpleData( sysarg, enCommonRankType_SpaceTrialWeek, SpaceTrialCfg.weekRank )
	SendCommonRankSimpleData( sysarg, enCommonRankType_SpaceTrialWeek )
end


function CheckEnterSpaceTrial( sysarg )
	--print("CheckEnterSpaceTrial...")
	if not CheckActorDailyDoneTimes( sysarg, enDailyOpTimes_SpaceTrial, 0 ) then
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.COM0021,ttFlyTip)
		return false
	end
	return true
end

function BeforeEnterSpaceTrial( sysarg )
	--print("BeforeEnterSpaceTrial...")
	AddActorDailyDoneTimes( sysarg, enDailyOpTimes_SpaceTrial, 0, 1 ) 				--进入次数+1
	return true
end

--[[开始刷出当前需要打的eBOSS
要刷出BOSS的playtime=配置的playtime + addPlayTime
]]
function FreshSpaceTrialBoss( fubenPtr, addPlayTime )
	Fuben.unregScriptCallback( fubenPtr, "SpaceTrialBossPlayerTimeOut")				--清除原定时器

	local bossIdx 		= Fuben.getFbValue( fubenPtr, SPACETRIAL_BOSS_IDX_PLAYING )
	local newBossIdx 	= bossIdx + 1
	Fuben.setFbValue( fubenPtr, SPACETRIAL_BOSS_IDX_PLAYING,  newBossIdx) 			--开始击杀第N个BOSS(放在这里，用来判断是否打完最后一个BOSS)
	local bossCfg = SpaceTrialCfg.boss[newBossIdx]
	if not bossCfg then
		return
	end

	local allPlayTime = addPlayTime+bossCfg.playTime
	local now = System.getCurrMiniTime()
	local fubenHandle = Fuben.getFubenHandle( fubenPtr )

	Fuben.setFbValue( fubenPtr, SPACETRIAL_BOSS_BEGINPLAYTIME, now )				--与第N个BOSS的开始战斗的时间
	Fuben.setFbValue( fubenPtr, SPACETRIAL_BOSS_ALLPLAYTIME, allPlayTime )			--与第N个BOSS的总的战斗的时间
	FreshCommonMonsters( { bossCfg }, fubenHandle, true )
	--print("FreshSpaceTrialBoss, newBossIdx="..newBossIdx..", beginPlayTime="..now..", allPlayTime="..allPlayTime)

	Fuben.regScriptTimer2S( fubenPtr, 0, allPlayTime*1000, allPlayTime*1000, 1, "SpaceTrialBossPlayerTimeOut")			--一段时间后，执行刷怪1次
end

function OpenSpaceTrialPanel( sysarg )
	if not IsInSpaceTrial( sysarg ) then
		return
	end

	local dDvar = Actor.getDyanmicVar(sysarg)

	local activityType 	= 1 			--活动
	local activityId 	= enRightPanelActivity_SpaceTrial

	local fubenPtr 		= Actor.getFubenPrt( sysarg )
	local now			= System.getCurrMiniTime()
	local bossIdx 		= Fuben.getFbValue( fubenPtr, SPACETRIAL_BOSS_IDX_PLAYING )
	local beginPlayTime = Fuben.getFbValue( fubenPtr, SPACETRIAL_BOSS_BEGINPLAYTIME )
	local allPlayTime   = Fuben.getFbValue( fubenPtr, SPACETRIAL_BOSS_ALLPLAYTIME )
	--print("OpenSpaceTrialPanel, bossIdx="..bossIdx..", beginPlayTime="..beginPlayTime..", allPlayTime="..allPlayTime)
	local restTime 		= allPlayTime - ( now - beginPlayTime )
	if restTime < 0 then
		restTime = 0
	end

	local killScore = Fuben.getFbValue( fubenPtr, SPACETRIAL_BOSS_KILLSCORE)

	local panelInfo 	= {}
	panelInfo.sts 		= 1  										--进行中
	panelInfo.title 	= Lang.ScriptTips.SpaceTrialName
	panelInfo.timeTitle = Lang.ScriptTips.panelCont01			--剩余时间
	panelInfo.restTime	= restTime

	panelInfo.contentTitle 	= ""  			--不用显示
	panelInfo.contents 		= {}
	panelInfo.contents[1]	= string.format( Lang.ScriptTips.panelCont10, bossIdx )
	panelInfo.contents[2]	= string.format( Lang.ScriptTips.panelCont16, killScore )

	panelInfo.awardTitle = Lang.ScriptTips.panelCont06
	panelInfo.awards 	 = SpaceTrialCfg.killBossAwards[bossIdx]

	panelInfo.buttons   	= {}
	panelInfo.buttons[1]	= 1							--1：退出副本，2-单倍领奖，3-双倍领奖

	OpenActivityRightPanel( sysarg, activityType, activityId, panelInfo )
end

function InitSpaceTrialData( sysarg )
	
end

--[[
是否在血域试炼中
]]
function IsInSpaceTrial( sysarg )
	local fubenId = Actor.getFubenId( sysarg )
	--print("IsInSpaceTrial, fubenId="..fubenId)
	return SpaceTrialCfg.fubenId == fubenId
end

--[[
获取血域试炼本人的某个数值
]]
function GetSpaceTrialMyValue( sysarg, valueIdx )
	local sVar = Actor.getStaticVar(sysarg)
	if not sVar.SpaceTrialData then
		sVar.SpaceTrialData = {}
	end
	return sVar.SpaceTrialData[valueIdx] or 0
end

function SetSpaceTrialMyValue( sysarg, valueIdx, newValue )
	local sVar = Actor.getStaticVar(sysarg)
	if not sVar.SpaceTrialData then
		sVar.SpaceTrialData = {}
	end
	sVar.SpaceTrialData[valueIdx] = newValue
end

--[[
获取血域试炼首次击杀某个BOSS
]]
function GetSpaceTrialFirstKillBoss( sysarg, bossIdx )
	local sVar = Actor.getStaticVar(sysarg)
	if not sVar.SpaceTrialFirstKillBoss then
		sVar.SpaceTrialFirstKillBoss = {}
	end
	return sVar.SpaceTrialFirstKillBoss[bossIdx] or 0
end

function SetSpaceTrialFirstKillBoss( sysarg, bossIdx, newSts )
	local sVar = Actor.getStaticVar(sysarg)
	if not sVar.SpaceTrialFirstKillBoss then
		sVar.SpaceTrialFirstKillBoss = {}
	end
	sVar.SpaceTrialFirstKillBoss[bossIdx] = newSts
end


--本次打BOSS时间到了，退出
function SpaceTrialBossPlayerTimeOut( fubenPtr )
	--print("SpaceTrialBossPlayerTimeOut...")
	local actorId 	= Fuben.getOwnerId( fubenPtr )
	local actorPtr 	= Actor.getActorById( actorId )
	if actorPtr and IsInSpaceTrial( actorPtr ) then 		--玩家在线并且在副本中
		OnSpaceTrialOver( actorPtr, fubenPtr, 2 )			--通关退出
	end
	local fubenHandle = Fuben.getFubenHandle( fubenPtr )
	Fuben.setFubenTime( fubenHandle, 1 )					--该BOSS时间到，尚未击杀，关闭副本
end

function OnSpaceTrialOver( sysarg, fubenPtr, sts )
	--print("OnSpaceTrialOver，sts="..sts)
	local panelInfo = {}
	panelInfo.subActivityId = 0
	panelInfo.sts 		= sts
	panelInfo.awards 	= {}
	local awardsMerged = GetFubenAwardsMerged( fubenPtr )
	for k,awardMerged in pairs( awardsMerged or {} ) do
		local award = {}
		award.type 		= awardMerged.type
		award.id 		= awardMerged.id
		award.count		= awardMerged.count
		award.quality	= awardMerged.qualit
		award.bind		= awardMerged.bind
		table.insert( panelInfo.awards, award )
	end

	PassActivityRightPanel( sysarg, 1, enRightPanelActivity_SpaceTrial, panelInfo )
	Actor.exitFuben( sysarg )						--打完退出（此时副本尚未被撤销，因为有一段延迟撤销时间）

	local actorName = Actor.getName( sysarg )
	local actorId 	= Actor.getActorId( sysarg )
	local bossIdx 	= Fuben.getFbValue( fubenPtr, SPACETRIAL_BOSS_IDX_PLAYING )
	System.sendCommonLog( GameLog.clSpaceTrialOver, actorId, actorName, sts, bossIdx, 0,'','', Lang.ScriptTips.SpaceTrialLog05 )
end

function GetSpaceTrialBossCfg( bossId )
	for bossIdx, bossCfg in ipairs( SpaceTrialCfg.boss ) do
		if bossCfg.monsterId == bossId then
			return bossCfg
		end
	end
	return nil
end

--[[
--sysarg:归属玩家
--lastHitKiller：最后一击玩家
注意：怪物死亡时，玩家可能不在线，要确保副本进度能够继续进行
]]
function OnSpaceTrialBossDie( monster, sysarg, monId, lastHitKiller )
	local bossCfg = GetSpaceTrialBossCfg( monId )
	if not bossCfg then
		return
	end

	local fubenPtr = Actor.getFubenPrt( monster )
	--print("OnSpaceTrialBossDie, monId="..monId..", bossIdx="..bossCfg.idx..", score="..bossCfg.score)
	GiveSpaceTrialKillBossAwards( sysarg, fubenPtr, bossCfg.idx ) 		--击杀奖励
	ProcSpaceTrialWeekScoreRank( sysarg, bossCfg.score )

	local killScore = Fuben.getFbValue( fubenPtr, SPACETRIAL_BOSS_KILLSCORE)
	Fuben.setFbValue( fubenPtr, SPACETRIAL_BOSS_KILLSCORE, killScore+bossCfg.score )
	
	local now = System.getCurrMiniTime()
	local bossIdx 		= Fuben.getFbValue( fubenPtr, SPACETRIAL_BOSS_IDX_PLAYING )
	if bossIdx >= #SpaceTrialCfg.boss then			--成功打完最后一个BOSS，成功通关
		OnSpaceTrialOver( sysarg, fubenPtr, 1 )		--全部打完算成功
		return
	end

	local beginPlayTime = Fuben.getFbValue( fubenPtr, SPACETRIAL_BOSS_BEGINPLAYTIME )
	local allPlayTime   = Fuben.getFbValue( fubenPtr, SPACETRIAL_BOSS_ALLPLAYTIME )
	--print("OnSpaceTrialBossDie, bossIdx="..bossIdx..", beginPlayTime="..beginPlayTime..", allPlayTime="..allPlayTime)

	local lastPlayTime 	= allPlayTime - ( now - beginPlayTime )		--lastPlayTime要累加到下一个BOSS的playtime中
	FreshSpaceTrialBoss( fubenPtr, 0 )		--刷出下一个BOSS(不叠加)
end

--BOSS mob 处理
function OnSpaceTrialBossMob(monster, monId, sceneId, x, y)
	--print("OnSpaceTrialMob, monId="..monId)
	local fubenPtr = Actor.getFubenPrt( monster )
	local actorId 	= Fuben.getOwnerId( fubenPtr )
	local actorPtr 	= Actor.getActorById( actorId )
	if actorPtr and IsInSpaceTrial( actorPtr ) then 			--玩家在线并且在副本中
		OpenSpaceTrialPanel( actorPtr )
	end
end

function GiveSpaceTrialKillBossAwards( sysarg, fubenPtr, bossIdx )
	--print("GiveSpaceTrialKillBossAwards, bossIdx="..bossIdx)
	local killAwards 		= SpaceTrialCfg.killBossAwards[bossIdx]
	local firstKillAwards 	= SpaceTrialCfg.firstKillBossAwards[bossIdx]

	if killAwards then
		GiveCommonAward( sysarg, killAwards, GameLog.clSpaceTrialKillAwards, Lang.ScriptTips.SpaceTrialLog03 )
		MergeFubenAwards( fubenPtr, killAwards )
	end

	if firstKillAwards then
		local hasFirstKill = GetSpaceTrialFirstKillBoss( sysarg, bossIdx )
		--print("GiveSpaceTrialKillBossAwards, hasFirstKill="..hasFirstKill)
		if hasFirstKill < 1 then
			SetSpaceTrialFirstKillBoss( sysarg, bossIdx, 1 )			--设置为已领取
			GiveCommonAward( sysarg, firstKillAwards, GameLog.clSpaceTrialFirstKillAwards, Lang.ScriptTips.SpaceTrialLog04 )
			MergeFubenAwards( fubenPtr, firstKillAwards )
			--print("SpaceTrialFirstKillBossAwards, actorId="..Actor.getActorId( sysarg )..", bossIdx="..bossIdx)
		end
	end
end


--[[
]]
function ProcSpaceTrialWeekScoreRank( sysarg, addScore )
	local actorId 	= Actor.getActorId( sysarg )
	--print("ProcSpaceTrialWeekScoreRank, actorId="..actorId..", addScore="..addScore)

	local job 		= Actor.getIntProperty( sysarg, PROP_ACTOR_VOCATION )
	UpdateCommonRankValueById( actorId, SpaceTrialWeekRank, addScore )				--积分累加
	SetCommonRankColumnValueById( actorId, SpaceTrialWeekRank, 0, 0,  Actor.getName(sysarg) )
	SetCommonRankColumnValueById( actorId, SpaceTrialWeekRank, 0, 1,  0 )			--留空，无意义
	SetCommonRankColumnValueById( actorId, SpaceTrialWeekRank, 0, 2,  job )
end

InitSpaceTrialWeekRank()
ResisterSpaceTrialProc()

